<?php

namespace app\admin\controller;

use org\Auth;
use think\Controller;
use think\Db;
use think\Session;


class Main extends Controller
{

    protected $not_check;

    /**
     * 初始化
     */
    public function _initialize()
    {
        $module = $this->request->module();
        $username = session('username');
        if (empty($username)) {
            $this->redirect('admin/user/login');
        }
        //排除权限
        $this->not_check = config('not_check');
        $this->checkAuth();
        $this->getMenu();
    }

    /**
     * 权限检查
     * @return bool
     */
    protected function checkAuth()
    {

        if (!Session::has('user_id')) {
            $this->redirect('admin/login/index');
        }

        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();
        // 排除权限
        $not_check = $this->not_check;
        $str = strtolower($module . '/' . $controller . '/' . $action);
        if (!in_array($str, $not_check)) {
            $auth = new Auth();
            $admin_id = Session::get('user_id');
            if (!$auth->check($module . '/' . $controller . '/' . $action, $admin_id) && $admin_id != 1) {
                $this->error('没有权限', '');
            }
        }
    }

    /**
     * 获取侧边栏菜单
     */
    protected function getMenu()
    {
        $menu = [];
        $admin_id = Session::get('user_id');
        $auth = new Auth();
        $auth_rule_list = Db::name('auth_rule')->where('status', 1)->order('sort asc')->select();
        foreach ($auth_rule_list as $value) {
            if ($auth->check($value['name'], $admin_id) || $admin_id == 1) {
                $menu[] = $value;
            }
        }
        $menu = !empty($menu) ? get_tree_arr3($menu, 0) : [];
//        p($menu);die;
        $this->assign('menu', $menu);
    }

    /**
     * 获取基础字典数据
     * @param string $table
     * @param string $where
     * @param string $order
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDictionary($table = '', $where = '', $order = '')
    {
        if (empty($table)) {
            return [];
        }
        return Db::name($table)->where($where)->order($order)->select();
    }

    /**
     * 获取当前用户公司下的员工角色
     * @param string $company_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRole($company_id = '')
    {
        $where['company_id'] = $company_id ? $company_id : isession('company_id');
        $where['flag'] = 1;
        $where['level'] = ['>', 2];
        $role = Db::name('auth_group')
            ->field('id,title')
            ->where($where)
            ->select();
        return $role;
    }

    /**
     * 获取指定角色下的用户列表
     * @param string $role_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserList($role_id = '')
    {
        $where['status'] = 1;
        $where['super'] = ['>', 2];
        $where['flag'] = 1;
        $where['role_id'] = $role_id;
        $user = Db::name('user')
            ->field('id,username,truename')
            ->where($where)
            ->select();
        return $user;
    }

    /**
     * 获取指定用户下的支付账号
     * @param string $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAccount($user_id = '')
    {
        $account = Db::name('user_account')
            ->where('user_id', $user_id)
            ->select();
        if (checkArr($account) == false) {
            return [];
        }
        $account_ids = join(',', array_column($account, 'account_id'));
        $where['id'] = ['in', $account_ids];
        $where['status'] = 1;
        $accounts = Db::name('pay_account')
            ->where($where)
            ->select();
        return $accounts;
    }

    /**
     * 获取物流公司
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogistics()
    {
        $where['status'] = 1;
        $where['raw'] = 1;
        $list = Db::name('logistics')
            ->where($where)
            ->order('id asc')
            ->select();

        checkArr($list) && $list = arrayCombine($list, 'id');

        $where1['raw'] = 2;
        $where1['company_id'] = isession('company_id');
        $logcom = Db::name('logistics')->field('id,status,pid')->where($where1)->select();

        if (checkArr($logcom)) {
            foreach ($logcom as $value) {
                if (isset($list[$value['pid']]) && $value['status'] == 2) {
                    unset($list[$value['pid']]);
                }
            }
        }
        return $list;
    }

    /**
     * 根据物流id获取物流信息
     * @param string $id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogisticsById($id = '')
    {
        $where['id'] = $id;
        return Db::name('logistics')->where($where)->order('id asc')->find();
    }

    /**
     * 获取物流公司货运方式
     * @param string $logistics_id
     * @param string $short
     * @param string $company_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLogisticShips($logistics_id = '', $short = '')
    {
        $where['short'] = $short;
        $where['logistics_id'] = $logistics_id;
        $where['type'] = 1;
        return Db::name('logistics_ship')
            ->field('method_code,cn_name')
            ->where($where)
            ->order('method_code asc')
            ->select();
    }

    /**
     * 获取当前公司下的所有用户
     * @param string $company_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllUser($company_id = '')
    {
        $where['company_id'] = $company_id ? $company_id : isession('company_id');
        $where['status'] = 1;
        $where['flag'] = 1;
        $where['super'] = ['>', 2];
        $user = Db::name('user')
            ->field('id,username,truename,role_id')
            ->where($where)
            ->select();
        return $user;
    }

    /**
     * 获取指定id下当前公司的角色列表
     * @param string $id
     * @param int $level
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRoleById($id = '', $level = 1)
    {
        $where['flag'] = 1;
        $where['id'] = ['in', $id];
        $where['level'] = ['>', $level];
        $role = Db::name('auth_group')
            ->field('id,title')
            ->where($where)
            ->select();
        return $role;
    }

    /**
     * 组装亚马逊产品url
     * @param $shop_id
     * @param string $asin
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function makeAmazonUrl($shop_id, $asin = '')
    {
        $store = DB::name('amazon_store')->where('id', $shop_id)->find();
        return $store['org'] . "/dp/" . $asin;
    }

    /**
     * 获取亚马逊有效店铺列表
     * @param string $company_id
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAmazonStore($company_id = '')
    {
        $where['company_id'] = $company_id ? $company_id : isession('company_id');
        $where['status'] = 1;
        $res = DB::name('amazon_store')->where($where)->select();
        return arrayCombine($res, 'id');
    }

    /**
     * 获取当前用户下的有效店铺
     * @param int $type
     * @param string $company_id
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getStoreByUser($type = 1, $company_id = '')
    {
        if (isession('super') > 3) {
            $where['type'] = $type;
            $where ['user_id'] = isession('user_id');
            $res = DB::name('store_user')->where($where)->select();
            if (checkArr($res) == false) {
                return [];
            }
            $store_id = join(',', array_unique(array_column($res, 'account_id')));
        }

        switch ($type) {
            case 1://亚马逊店铺
                $where = isession('super') > 3 ? "status = 1 AND id IN (" . $store_id . ") AND company_id = " . $company_id : "status = 1 AND company_id = " . $company_id;
                $store = DB::name('amazon_store')->where($where)->select();
                break;
            case 2://ebay店铺
                $store = [];
                break;
            case 3://速卖通店铺
                $store = [];
                break;
            case 4://wish店铺
                $store = [];
                break;
        }
        return checkArr($store) ? arrayCombine($store, 'id') : [];
    }

    /**
     * 上传图片
     * @param $file $_FILES['file']
     * @param $dir '/files/' . isession('user_id') . '/wallet/' . date("Y-m-d", time()) . "/";
     * @param $exts array('jpg','jpeg','png');
     * @return array
     */
    public function imgUploads($file, $dir, $exts)
    {
        $path = server('DOCUMENT_ROOT') . $dir;
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                return array("res" => false, "msg" => "没有权限创建目录");
            }
        }
        $fname = htmlspecialchars($file["name"], ENT_QUOTES);
        if ($file["error"] > 0) {
            return array("res" => false, "msg" => "文件  " . $fname . " 上传时出错");
        }

        $extension = "." . strtolower(pathinfo($fname, PATHINFO_EXTENSION));

        $ext = '.' . join('.', $exts) . "." . strtoupper(join('.', $exts));
        if (strpos($ext, $extension) !== false) {
        } else {
            return array("res" => false, "msg" => "只允许上传" . join(',', $exts) . "格式的图片");
        }

        $ftmp_name = $file["tmp_name"];
        //对临时文件名加密，用于后面生成复杂的新文件名
        $md5 = md5_file($ftmp_name);
        //取得图片的大小
        $imageInfo = getimagesize($ftmp_name);
        $rawImageWidth = $imageInfo[0];
        $rawImageHeight = $imageInfo[1];
        //文件名
        $name = "$md5{$extension}";

        //加入图片文件没变化到，也就是存在，就不必重复上传了，不存在则上传
        if (file_exists($path . $name)) {
            $ret = true;
            $rsize = false;
        } else {
            $ret = move_uploaded_file($ftmp_name, $path . $name);
            $rsize = true;
        }

        if ($ret === false) {
            return array("res" => false, "msg" => "上传失败，请重试");
        }
        $files = array(
            'name' => $name,
            'path' => $dir . $name,
            'size' => $file['size'],
            'postfix' => trim($extension, "."),
            'original' => $file['name'],
            'rsize' => $rsize
        );
        return array("res" => true, "msg" => '上传成功', 'files' => $files);
    }

    /**
     * 获取现有货币的汇率
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getRate()
    {
        //获取常用货币单位
        $unit = DB::name('unit')->select();
        foreach ($unit as $key => $value) {
            if ($value['sign'] == 'CNY') {//人民币汇率不查
                $rate[$value['sign']] = $value;
                $rate[$value['sign']]['rate_time'] = date("Y-m-d");
            } elseif ($value['rate_time'] == date("Y-m-d")) {//当天汇率
                $rate[$value['sign']] = $value;
            } else {//过期汇率，更新
                $rate[$value['sign']] = $value;
                $rate[$value['sign']]['rate'] = $this->getCNY($value['sign']);
                $rate[$value['sign']]['rate_time'] = date("Y-m-d");
            }
        }
        return $rate;
    }

    /**
     * 获取总价汇率转入人民币数值,同步更新数据库
     * @param string $unit
     * @param string $type
     * @param string $return
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getCNY($unit = "EUR", $type = 'update', $return = '')
    {
        if ($unit == '') {
            return 0;
        }
        $url = "http://op.juhe.cn/onebox/exchange/currency?from=CNY&to=" . $unit . "&key=0197bad94d6d8d8dd9cb71458cda4ff2";
        $cny = json_decode(request_get($url), true);
        $rate = isset($cny['result'][0]['result']) ? $cny['result'][0]['result'] : 0;
        if ($type == 'update') {
            DB::name('unit')->where('sign', $unit)->update(['rate' => $rate, 'rate_time' => date("Y-m-d")]);
        } else {
            $data['name'] = isset($cny['result'][0]['currencyT_Name']) ? $cny['result'][0]['currencyT_Name'] : '';
            $data['sign'] = $unit;
            $data['rate'] = $rate;
            $data['rate_time'] = date("Y-m-d");
            DB::name('unit')->insert($data);
            if ($return) {
                return $data;
            }
        }
        return $rate;
    }

    /**
     * csv导入,此格式每次最多可以处理1000条数据
     * @param $csv_file
     * @return array
     */
    public function input_csv($csv_file)
    {
        $out = array();
        $n = 0;
        while ($data = fgetcsv($csv_file, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        return $out;
    }

    /**
     * csv导入,单列数据，此格式每次最多可以处理1000条数据
     * @param $csv_file
     * @return array
     */
    public function input_OnceCsv($csv_file)
    {
        $out = array();
        $n = 0;
        while ($data = fgetcsv($csv_file, 10000)) {
            isset($data[0]) && $out[$n] = $data[0];
            $n++;
        }
        return $out;
    }

    /**
     * 获取总公司下的子公司列表
     * @param string $company_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCompany($company_id = '')
    {
        $company = DB::name('company')->field('id,name')->where(['pid' => $company_id, 'type' => 2])->select();
        if (!checkArr($company)) {
            return [];
        }
        //获取总公司下的子公司列表
        $where['status'] = 1;
        $where['flag'] = 1;
        $where['type'] = 2;
        $where['company_id'] = ['in', join(',', array_column($company, 'id'))];
        $company_ids = DB::name('user')->distinct(true)->field('company_id')->where($where)->select();
        if (!checkArr($company_ids)) {
            return [];
        }
        $company_ids = array_column($company_ids, 'company_id');

        $companys = [];
        foreach ($company as $value) {
            if (in_array($value['id'], $company_ids)) {
                $companys[] = $value;
            }
        }
        return $companys;


    }

    /**
     * 获取某个公司全部订单毛利
     * @param string $start
     * @param string $end
     * @param string $company_id
     * @return float|int
     */
    public function getOrderProfit($start = '', $end = '', $company_id = '')
    {
        //亚马逊订单毛利
        $awhere['order_status'] = 8;
        $awhere['create_time'] = ['>=', $start];
        $awhere1['create_time'] = ['<=', $end];
        $awhere['company_id'] = $company_id;
        $amazon = DB::name('amazon_order')->where($awhere)->where($awhere1)->sum('profit');

        $total = $amazon;
        return $total;
    }

    /**
     * 获取有效采集平台信息
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPlatform(){
        $where['flag'] = 1;
        $where['type'] = ['neq', 3];
        return Db::name('platform')->where($where)->order('odx asc')->select();
    }
}
